package com.kite.videolib

import android.content.Context
import android.graphics.SurfaceTexture
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.Surface
import android.view.TextureView
import android.widget.FrameLayout
import com.kite.videolib.player.R
import tv.danmaku.ijk.media.player.IMediaPlayer
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import java.io.IOException

class VideoPlayerView : FrameLayout {
    private val TAG = "com.kite.videolib.VideoPlayerView"
    private val mTextureView: TextureView
    private var mSurface: Surface? = null
    var listener: IMediaPlayer.OnPreparedListener? = null
    var refreshListener: FrameRefreshListener? = null

    var mPath: String? = null
    var mMediaPlayer: IjkMediaPlayer? = null

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
            super(context, attrs, defStyleAttr) {
        LayoutInflater.from(context).inflate(R.layout.view_layout_video_player, this, true)
        mTextureView = findViewById(R.id.view_video_player_sv)
        initTextureView()
        Log.d(TAG, "initSurfaceView: init")
    }

    private fun initIjkPlay() {
        mMediaPlayer?.stop()
        mMediaPlayer?.setDisplay(null)
        mMediaPlayer?.release()
        val ijkMediaPlayer = IjkMediaPlayer()
        IjkMediaPlayer.native_setLogLevel(IjkMediaPlayer.IJK_LOG_DEBUG)
        //开启硬解码
//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
        mMediaPlayer = ijkMediaPlayer
        addListener()
    }

    private fun addListener() {
        mMediaPlayer?.setOnBufferingUpdateListener { _, _ ->
            Log.d(TAG, "setOnBufferingUpdateListener: ")
        }
        mMediaPlayer?.setOnCompletionListener {
            Log.d(TAG, "setOnCompletionListener: ")
        }
        mMediaPlayer?.setOnPreparedListener {
            Log.d(TAG, "setOnPreparedListener: ")
            it.pause()
            it.seekTo(0)
            listener?.onPrepared(it)
        }
        mMediaPlayer?.setOnInfoListener { p0, p1, p2 ->
            Log.d(TAG, "setOnInfoListener: ")
            false
        }
        mMediaPlayer?.setOnVideoSizeChangedListener { p0, p1, p2, p3, p4 ->
            Log.d(TAG, "setOnVideoSizeChangedListener: ")
        }
        mMediaPlayer?.setOnErrorListener { _, p1, p2 ->
            Log.d(TAG, "setOnErrorListener: ")
            false
        }
        mMediaPlayer?.setOnSeekCompleteListener {
            Log.d(TAG, "setOnSeekCompleteListener: ")
        }
        mMediaPlayer?.setOnTimedTextListener(IMediaPlayer.OnTimedTextListener { p0, p1 ->
            Log.d(
                TAG,
                "onTimedText: ${p1?.text}"
            )
        })

    }

    private fun initTextureView() {
        mTextureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(
                surface: SurfaceTexture,
                width: Int,
                height: Int
            ) {
                this@VideoPlayerView.mSurface = Surface(surface);
                load()
                Log.d(TAG, "onSurfaceTextureAvailable:")
            }

            override fun onSurfaceTextureSizeChanged(
                surface: SurfaceTexture,
                width: Int,
                height: Int
            ) {
                Log.d(TAG, "onSurfaceTextureSizeChanged:")
            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                surface.release()
                Log.d(TAG, "onSurfaceTextureDestroyed:")
                return false
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
                Log.d(TAG, "onSurfaceTextureUpdated:")
                refreshListener?.onSurfaceTextureUpdated(surface, mMediaPlayer!!)
            }

        }
    }

    /**
     * 加载视频
     */
    private fun load() {
        //每次都要重新创建IMediaPlayer
        initIjkPlay()
        Log.d(TAG, "initIjkPlay:2 ")
        Log.d(TAG, "surfaceCreated: ")
        try {
            mMediaPlayer!!.dataSource = mPath
            //循换播放
            mMediaPlayer!!.isLooping = true;
        } catch (e: IOException) {
            Log.d(TAG, "load:${e.message} ")
            e.printStackTrace()
        }
        //给mediaPlayer设置视图
        mMediaPlayer!!.setSurface(mSurface);
        mMediaPlayer!!.prepareAsync()
    }

    fun start() {
        mMediaPlayer?.start()
    }

    fun pause() {
        mMediaPlayer?.pause()
    }

    fun seekTo(index: Long) {
        mMediaPlayer?.seekTo(index)
    }

    fun setPathAndLoadData(path: String) {
        mPath = path
        load()
    }

    fun setVolume(left: Float, right: Float) {
        mMediaPlayer?.setVolume(left, right)
    }

    fun release() {
        mMediaPlayer?.stop()
        mMediaPlayer?.release()
    }

    interface FrameRefreshListener {
        fun onSurfaceTextureUpdated(surface: SurfaceTexture, ijkMediaPlayer: IjkMediaPlayer)
    }

}